#!/usr/bin/env python3
"""
演示如何使用 HTTP API 获取设备列表
"""

import httpx
import asyncio
import json


async def demo_get_devices():
    """演示获取设备列表"""
    
    print("🔧 IoT MCP 设备列表 HTTP API 演示")
    print("=" * 50)
    
    # 演示 1: 获取运行中的设备
    print("\n📋 演示 1: 获取运行中的设备")
    print("-" * 30)
    
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(
                "http://localhost:8000/api/devices",
                params={"state": "运行中"}
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 成功获取到 {data['count']} 个运行中的设备:")
                
                for device in data['devices']:
                    print(f"   📱 {device['device_name']}")
                    print(f"      类型: {device['device_type']}")
                    print(f"      位置: {device['place_name']}")
                    print(f"      状态: {device['state']}")
                    print()
            else:
                print(f"❌ 请求失败: {response.status_code}")
                print(f"   错误信息: {response.text}")
                
    except httpx.ConnectError:
        print("❌ 连接失败: 请确保服务正在运行 (http://localhost:8000)")
    except Exception as e:
        print(f"❌ 其他错误: {e}")
    
    # 演示 2: 获取指定场地的设备
    print("\n📋 演示 2: 获取 4#411 场地的设备")
    print("-" * 30)
    
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(
                "http://localhost:8000/api/devices",
                params={"place_name": "4#411"}
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 成功获取到 {data['count']} 个 4#411 场地的设备:")
                
                for device in data['devices']:
                    print(f"   📱 {device['device_name']} ({device['device_type']})")
                print()
            else:
                print(f"❌ 请求失败: {response.status_code}")
                
    except Exception as e:
        print(f"❌ 错误: {e}")
    
    # 演示 3: 组合查询
    print("\n📋 演示 3: 获取 4#411 场地运行中的照明设备")
    print("-" * 30)
    
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.get(
                "http://localhost:8000/api/devices",
                params={
                    "place_name": "4#411",
                    "device_type": "照明",
                    "state": "运行中"
                }
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 成功获取到 {data['count']} 个符合条件的设备:")
                
                for device in data['devices']:
                    print(f"   💡 {device['device_name']}")
                    print(f"      编号: {device['device_no']}")
                    print(f"      位置: {device['place_name']}")
                    print()
            else:
                print(f"❌ 请求失败: {response.status_code}")
                
    except Exception as e:
        print(f"❌ 错误: {e}")


def show_api_info():
    """显示 API 信息"""
    print("\n📚 API 使用说明")
    print("=" * 50)
    print("端点: GET /api/devices")
    print("参数:")
    print("  - device_type: 设备类型 (可选)")
    print("  - place_name: 场地名称 (可选)")
    print("  - state: 设备状态 (可选)")
    print("\n示例:")
    print("  curl 'http://localhost:8000/api/devices?state=运行中'")
    print("  curl 'http://localhost:8000/api/devices?place_name=4#411'")
    print("  curl 'http://localhost:8000/api/devices?device_type=照明&state=运行中'")


async def main():
    """主函数"""
    try:
        await demo_get_devices()
        show_api_info()
        
        print("\n🎉 演示完成!")
        print("\n💡 提示:")
        print("   - 确保服务正在运行: python main.py")
        print("   - 查看完整文档: HTTP_API_README.md")
        print("   - 运行测试: python test_http_api.py")
        
    except KeyboardInterrupt:
        print("\n\n⏹️ 演示被用户中断")
    except Exception as e:
        print(f"\n❌ 演示过程中发生错误: {e}")


if __name__ == "__main__":
    asyncio.run(main())
